package org.jugile.jsontmpl;

import java.util.HashMap;
import java.util.Map;

import org.jugile.jsontmpl.domain.*;
import org.jugile.util.Jugile;
import org.jugile.util.Props;
import org.jugile.util.Vo;

public class JsonTmpl extends Jugile {

	public synchronized static Vo get(String filename, int idx) {
		Obj o = getTemplates().getObj(filename);
		return o.toVo(idx);
	}
	
	public synchronized static Vo get(String filename, Object model) {
		if (model == null) fail("null model: " + filename);
		Obj o = getTemplates().getObj(filename);
		EvalCtx ctx = new EvalCtx();
		ctx.push(model);
		return o.toVo(ctx);
	}
	
	public synchronized static Obj getTmpl(String filename) {
		return getTemplates().getObj(filename);
	}

	private static JsonTmpl templates = null; 
	private synchronized static JsonTmpl getTemplates() {
		if (templates != null) return templates;
		templates = new JsonTmpl();
		return templates;
	}
	
	private Domain d;
	private JsonTmpl() {
		d = Domain.getDomain("empty");		
	}

	private boolean isProduction() { return Props.isProduction(); }
	
	private Map<String,Obj> objs = new HashMap<String,Obj>(); 
	private synchronized Obj getObj(String fname) {
		Obj o = null;
		if (isProduction()) {
			// check cache
			o = objs.get(fname);
			if (o != null) return o;
			// not found
			o = readModelFile(fname);
			objs.put(fname, o);
			return o;
		}
		print("=== not production");
		return readModelFile(fname);
	}
	
	private Obj readModelFile(String fname) {
		print("===== readModelFile: " +fname);
		Obj o = d.getRootObj(fname);
		if (o != null) o.delete();
		Ctx ctx = new Ctx();
		return d.parseXmlFile(ctx,fname);
	}
	
}
